<template>
  <el-card class="blog-list-card">
    <!-- 添加发布博客按钮 -->

    <div slot="header">
      <!-- <span>博客列表</span> -->
      <span class="card-title" style="font-size: 1.5em; margin: 20px 0"
        >博客列表
      </span>
      <el-button
        class="publish-btn"
        type="primary"
        @click="$router.push('/blog/create')"
        icon="el-icon-plus"
      >
        发布新博客
      </el-button>
    </div>

    <el-input
      placeholder="搜索博客标题"
      v-model="searchQuery"
      class="search-input"
      @keyup.enter.native="loadBlogs"
    >
      <el-button
        slot="append"
        icon="el-icon-search"
        @click="loadBlogs"
      ></el-button>
    </el-input>

    <div class="blog-list">
      <el-card class="blog-item" v-for="blog in blogs" :key="blog.id">
        <div class="blog-title">
          <router-link :to="`/blog/${blog.id}`">{{ blog.title }}</router-link>
        </div>
        <div class="blog-meta">
          <span>作者: {{ blog.username }}</span>
          <span>发布时间: {{ blog.created_at }}</span>
        </div>
        <div class="blog-excerpt">
          {{
            blog.content.length > 150
              ? blog.content.substring(0, 150) + "..."
              : blog.content
          }}
        </div>
        <div class="blog-actions">
          <router-link
            :to="`/blog/${blog.id}`"
            class="read-more"
            icon="el-icon-arrow-right"
          >
            阅读全文
          </router-link>
          <div v-if="isOwner(blog.user_id)">
            <el-button
              type="text"
              size="small"
              @click="$router.push(`/blog/${blog.id}/edit`)"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              danger
              @click="handleDelete(blog.id)"
            >
              删除
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <div v-if="blogs.length === 0 && !loading" class="no-data">
      暂无博客数据
    </div>
    <el-pagination
      class="pagination"
      layout="prev, pager, next"
      :total="total ? total : 0"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handlePageChange"
    ></el-pagination>
  </el-card>
</template>

<script>
  export default {
    data() {
      return {
        blogs: [],
        total: 0,
        pageSize: 5,
        currentPage: 1,
        searchQuery: "",
        userId: null,
        loading: false,
        preSearchQuery: "",
      };
    },
    created() {
      // 获取当前登录用户ID
      const user = JSON.parse(localStorage.getItem("user") || "{}");
      this.userId = user.userId;

      this.loadBlogs();
    },
    methods: {
      async loadBlogs() {
        this.loading = true;
        try {
          if (this.searchQuery && this.searchQuery !== this.preSearchQuery) {
            this.currentPage = 1;
          }
          let url = `/blogs?page=${this.currentPage}&pageSize=${this.pageSize}`;
          if (this.searchQuery) {
            url += `&search=${this.searchQuery}`;
          }

          let result = await this.$axios.get(url);
          result = result.data;
          this.blogs = result.data;
          this.total = result.total;
          this.preSearchQuery = this.searchQuery;
        } catch (error) {
          this.$message.error("加载博客列表失败");
          console.error(error);
        } finally {
          this.loading = false;
        }
      },
      handlePageChange(page) {
        this.currentPage = page;
        this.loadBlogs();
      },
      isOwner(blogUserId) {
        return this.userId === blogUserId;
      },
      async handleDelete(blogId) {
        this.$confirm("确定要删除这篇博客吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            try {
              await this.$axios.delete(`/blog/${blogId}`);
              this.$message.success("删除成功");
              this.loadBlogs();
            } catch (error) {
              this.$message.error("删除失败");
              console.error(error);
            }
          })
          .catch(() => {
            this.$message.info("已取消删除");
          });
      },
    },
  };
</script>

<style scoped>
  .blog-list-card {
    max-width: 1000px;
    margin: 20px auto;
  }
  .publish-btn {
    float: right;
    padding: 3px 8px;
  }
  .publish-btn a {
    text-decoration: none;
  }
  .dark .publish-btn a {
    color: #d1d1d1;
  }
  .search-input {
    width: 100%;
    margin-bottom: 20px;
  }

  .blog-list {
    margin-bottom: 20px;
  }

  .blog-item {
    margin-bottom: 20px;
    transition: all 0.3s;
  }

  .blog-item:hover {
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  }

  .blog-title {
    font-size: 18px;
    margin-bottom: 10px;
  }

  .blog-title a {
    color: #333;
    text-decoration: none;
  }
  .dark .blog-title a {
    color: #d1d1d1;
  }

  .blog-title a:hover {
    color: #409eff;
  }

  .blog-meta {
    color: #666;
    font-size: 14px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
  }

  .blog-excerpt {
    color: #666;
    line-height: 1.6;
    margin-bottom: 15px;
  }

  .blog-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .read-more {
    color: #409eff;
    text-decoration: none;
  }

  .no-data {
    text-align: center;
    padding: 50px 0;
    color: #999;
  }

  .pagination {
    margin-top: 20px;
    text-align: center;
  }
</style>
